<?php

/***  Documentation

    Greqo Analytics API Class
    Last Update: $Date: 2009-10-01 04:39:01 +0000 (Thu, 01 Oct 2009) $
    Author: Tom at klenwell@gmail.com

DESCRIPTION
    Programmatic interface for Google Analytics service
  
USAGE


NOTES
    This class is designed to be compatible with PHP 4.  Disable strict error
    notices in PHP 5 or above.
    
    SESSION values
        $_SESSION['GDATA']['auth_token']
    
______________________________________________________________________________*/

// load base Greqo class
require_once('analytics.class.php');

class GreqoAnalyticsApi extends GreqoAnalytics
{
    // service settings
    var $service = 'analytics';
    var $service_url = 'https://www.google.com/analytics/feeds/data';
    
    // other constants
    var $day_sec = 86400;
    var $week_sec = 604800;


    /* MAGIC METHODS */
    // php4 constructor
    function GreqoAnalyticsApi($start_session=1)
    {
        $this->__construct($start_session);
        register_shutdown_function( array($this, '__destruct') );
    }


    // php5 constructor
    function __construct($ss=1)
    {
        // load parent class
        parent::__construct($ss);
        
        // additional settings
        $this->load_cacher();
    }
    
    
    // destructor
    function __destruct()
    {
        $this->debug(sprintf("%s END\n\n", __CLASS__));
    }
  

    /* ** PUBLIC METHODS ** */
    function get_report_xml($pid, $DimList, $MetricList, $start, $end=null, $sort=null, $max=5, $pprint=true)
    {
        if ( ! $this->gdata_auth_token )
            return $this->err('token required: call request_clientlogin_token');
        
        if ( is_null($end) ) $end = $start;
        if ( !$sort ) $sort = $MetricList[0];
        $dim_list = implode(',', $DimList);
        $met_list = implode(',', $MetricList);

        $GetDict = array(
            'start-date' => date('Y-m-d', strtotime($start)),
            'end-date' => date('Y-m-d', strtotime($end)),
            'dimensions' => $dim_list,
            'metrics' => $met_list,
            'sort' => $sort,
            'max-results' => $max,
            'ids' => sprintf('ga:%s', $pid),
            'prettyprint' => $pprint
        );
        
        $qstring = $this->_get_query_string($GetDict);
        $url = $this->service_url . $qstring;
        $HeaderList = array(
            'Authorization' => sprintf('GoogleLogin auth=%s', $this->gdata_auth_token)
        );
        
        $xml = $this->get($url, $HeaderList);
        return $xml;
    }
    
    function get_current_visitor_report($pid)
    {
        $DimList = array('ga:date');
        $MetricList = array('ga:visitors','ga:visits','ga:pageviews');
        $start = date('Y-m-d', time() - $this->day_sec);
        $end = date('Y-m-d');
        $xml = $this->get_report_xml($pid, $DimList, $MetricList, $start, $end);
        
        // parse
        $XmlDoc = $this->parse_xml($xml);
        
        // datasource data
        $DatasourceDict = array();
        foreach ( $XmlDoc->dxp_datasource[0]->tagChildren as $Node ) {
            if ( isset($Node->tagAttrs['name']) )
                $DatasourceDict[$Node->tagAttrs['name']] = $Node->tagAttrs['value'];
            else
                $DatasourceDict[$Node->tagName] = $Node->tagData;
        }
                
        // aggregates
        $AggregateDict = array();
        foreach ( $XmlDoc->dxp_aggregates[0]->tagChildren as $Node )
            $AggregateDict[$Node->tagAttrs['name']] = $Node->tagAttrs['value'];
        
        // detail
        $EntryDict = array();
        foreach ( $XmlDoc->entry as $EntryNode )
        {
            $DimDict = array();
            $MetricDict = array();
            
            foreach ( $EntryNode->dxp_dimension as $Dim )
                $DimDict[$Dim->tagAttrs['name']] = $Dim->tagAttrs['value'];
            
            foreach ( $EntryNode->dxp_metric as $Metric )
                $MetricDict[$Metric->tagAttrs['name']] = $Metric->tagAttrs['value'];

            $EntryDict[$DimDict['ga:date']] = array_merge($DimDict, $MetricDict);
        }
        
        return array(
            'datasource' => $DatasourceDict,
            'aggregate'  => $AggregateDict,
            'detail'     => $EntryDict
        );
    }
    
    function get_account_list($pprint=1)
    {
        $url = 'https://www.google.com/analytics/feeds/accounts/default';
        
        if ( ! $this->gdata_auth_token )
            return $this->err('token required: call request_clientlogin_token');

        $GetDict = array(
            'prettyprint' => $pprint
        );
        
        $qstring = $this->_get_query_string($GetDict);

        $HeaderList = array(
            'Authorization' => sprintf('GoogleLogin auth=%s', $this->gdata_auth_token)
        );
        
        if ( !$xml = $this->get($url, $HeaderList) )
            return null;
        
        return $this->_parse_account_xml($xml);
    }
    


    /* ** PRIVATE METHODS ** */
    function _parse_account_xml($xml)
    {
        // parse
        $XmlDoc = $this->parse_xml($xml);
        
        // meta data
        $total_results = $XmlDoc->opensearch_totalresults[0]->tagData;
        
        // profile detail 
        $ProfileDict = array();
        foreach ( $XmlDoc->entry as $EntryNode )
        {
            foreach ( $EntryNode->tagChildren as $Node ) {
                if ( isset($Node->tagAttrs['name']) )
                    $EntryDict[$Node->tagAttrs['name']] = $Node->tagAttrs['value'];
                else
                    $EntryDict[$Node->tagName] = $Node->tagData;
            }
            $ProfileDict[$EntryDict['title']] = $EntryDict;
        }
        
        if ( $total_results != count(array_keys($ProfileDict)) )
            trigger_error(
                sprintf( 'warning: totalResult property (%s) and profile count (%s) do not match',
                         $total_results,
                         count(array_keys($ProfileDict)) ) );
        
        return $ProfileDict;
    }
    
    function _get_query_string($Dict)
    {
        if ( !$Dict ) return '';
        
        $QDict = array();
        foreach ( $Dict as $k => $v )
            $QDict[] = sprintf('%s=%s', urlencode($k), urlencode($v));
        
        $qstring = implode('&', $QDict);
        return '?' . $qstring;
    }
    

} // end class

?>
